package com.rabbitmq.priority;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.common.Constant.NUM10;

// 消息优先级消费
@Slf4j
public class PriorityQueue {
    public static void main( String[] args )  {
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare("exchange.priority", "direct", true, false, null);
            Map<String, Object> arg = new HashMap<String, Object>();
            // 设置队列的最大优先级
            arg.put("x-max-priority", NUM10);
            channel.queueDeclare("queue.priority", true, false, false, arg);
            channel.queueBind("queue.priority", "exchange.priority", "routingKey");

            String message = "Hello World  10!";
            AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
            // 消息的优先级只能在0到x-max-priority进行设置
            builder.priority(NUM10);
            AMQP.BasicProperties properties = builder.build();
            // 消息发布，properties中有消息的优先级
            channel.basicPublish("exchange.priority", "routingKey", false,
                    properties, message.getBytes());

            ConnectionUtils.close(channel, connection);
        } catch (IOException e) {
            log.info("catch IOException");
        } catch (TimeoutException e) {
            log.info("catch TimeoutException");
        }
    }
}
